package com.kaifamiao.www.demo.do0905;

import java.sql.*;

public class Demo {
    public static void main(String[] args) {
        try {
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //连接数据库
            String url = "jdbc:mysql://localhost:3306/kfm";
            String user = "root";
            String password = "";
            Connection connection = DriverManager.getConnection(url,user,password);
            //创建statement 语句
            Statement statement = connection.createStatement();
            // 定义SQL语句
            String sql = "SELECT id,username user,password pass,createDate date FROM users";
            //执行SQL并返回
            ResultSet resultSet = statement.executeQuery(sql);
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            //1,getcolumnLable  getColumnName 区别
            //2, 输出结果集
            for (int i = 1;i <= columnCount;i++){
                String lable = metaData.getColumnLabel(i);
                System.out.print(lable +"\t\t");
            }
            System.out.println();
            //遍历解析结果
            while (resultSet.next()){
                int id = resultSet.getInt(1);
                String username = resultSet.getString("user");
                String pass = resultSet.getString(3);
                Date createDate = resultSet.getObject("date",Date.class);
                System.out.println(id + "\t\t" + username + "\t\t" +pass + "\t\t" + createDate);
            }

            // 关闭连接
            resultSet.close();
            statement.close();
            connection.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
